xquery version "1.0-ml";

import module namespace plib = "http://porvino.com/lib" at "/porvino/lib/lib.xqy";
import module namespace tags = "http://www.porvino.com/tags" at "/porvino/tags/tags.xqy";

let $cid := xdmp:get-request-field("cid")
let $host := xdmp:get-request-field("host")
let $did := xdmp:get-request-field("did")
let $dbase := xdmp:get-request-field("dbase")
let $tag := xdmp:get-request-field("tag")

return
    let $docpath := fn:concat("fn:doc('",$did,"')",$dbase)
    let $doc := xdmp:eval($docpath)
    let $insert-tag :=
        fn:concat(
            "xdmp:node-insert-child(",
                $docpath,
                "/tags[1],",
                "<tag>",
                fn:normalize-space($tag),
                "</tag>",
            ")"
        )
     let $insert-tags :=
        fn:concat(
            "xdmp:node-insert-child(",
                $docpath,
                ",",
                "<tags><tag>",
                fn:normalize-space($tag),
                "</tag></tags>",
            ")"
        )


    return
    if (
        fn:exists(
            $doc/tags/tag[fn:normalize-space(text()) = fn:normalize-space($tag)]
        )
    )
    then "already exists"
    else
        if (
            fn:exists(
                $doc/tags
            )
        )
        then
            let $t1 :=
                xdmp:eval($insert-tag)
            return
            tags:get-tag-control( $cid, $host, $did, $dbase, $tag)
        else
            let $t1 :=
                xdmp:eval($insert-tags)
            return
            tags:get-tag-control( $cid, $host, $did, $dbase, $tag)


           
           
              
